package com.tanhua.server.service;

import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.db.UserInfo;
import com.tanhua.dubbo.api.PublishApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.mongo.Publish;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.vo.MomentVo;
import com.tanhua.vo.PageResult;
import com.tanhua.vo.PublishVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
<<<<<<< HEAD
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

=======
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.management.relation.RelationService;
>>>>>>> acc7004 (第4天到第8天)
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @author： xtr
<<<<<<< HEAD
 * @date： 2021-03-10 20:43
=======
 * @date： 2021-03-13 19:25
>>>>>>> acc7004 (第4天到第8天)
 */
@Service
@Slf4j
public class MomentService {

    @Autowired
    private OssTemplate ossTemplate;

    @Reference
    private PublishApi publishApi;

    @Reference
    private UserInfoApi userInfoApi;
<<<<<<< HEAD
    /**
     * 动态发布
     * @param publishVo
     * @param imageContent
     */
    public void postMoment(PublishVo publishVo, MultipartFile[] imageContent) {
        log.info("开始发布动态");
        Long userId = UserHolder.getUserId();
        List<String> imageUrl = new ArrayList<>();
        if (imageContent!=null){
            try {
                for (MultipartFile multipartFile : imageContent) {
                    String url = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
                    log.info("上传的图片url：{}",url);
                    imageUrl.add(url);
                }
            } catch (IOException e) {
                throw new TanHuaException("上传图片失败");
            }
            Publish publish = new Publish();
            BeanUtils.copyProperties(publishVo,publish);
            publish.setUserId(userId);
            publish.setMedias(imageUrl);
            publishApi.add(publish);
            log.info("动态发布成功");
        }
=======

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 发布动态
     * @param vo
     */
    public void postMoment(PublishVo vo, MultipartFile[] imageContent) {
        log.info("开发发布动态.............");
        //1. 获取登陆用户id
        Long userId = UserHolder.getUserId();
        log.info("登陆用户的id={}", userId);
        //2. 循环遍历上传图片,List图片的url
        List<String> imageUrls = new ArrayList<String>();
        if(null != imageContent){
            try {
                for (MultipartFile file : imageContent) {
                    String url = ossTemplate.upload(file.getOriginalFilename(), file.getInputStream());
                    log.info("上传的图片：{}",url);
                    imageUrls.add(url);
                }
            }catch (IOException ex){
                throw new TanHuaException("上传图片失败");
            }
        }
        //3. 构建publish对象
        Publish publish = new Publish();
        BeanUtils.copyProperties(vo,publish);
        publish.setUserId(userId);
        publish.setMedias(imageUrls);
        log.info("动态的详情: {}", publish);
        // 调用服务发布动态
        publishApi.add(publish);
        log.info("发布动态成功...........");
>>>>>>> acc7004 (第4天到第8天)
    }

    /**
     * 查看好友动态
     * @param page
     * @param pagesize
     * @return
     */
<<<<<<< HEAD
    public PageResult<MomentVo> queryFriendPublishList(long page, long pagesize) {
        Long userId = UserHolder.getUserId();
        PageResult pageResult = publishApi.queryFriendPublishList(page,pagesize,userId);
        List<Publish> items = pageResult.getItems();
        //遍历结果集，获取用户详情
        List<MomentVo> voList = new ArrayList<>();
        if (items!=null){
            for (Publish publish : items) {
                Long publisherId = publish.getUserId();//发布者id，好友id
                //查询好友详情
                UserInfo userInfoById = userInfoApi.findUserInfoById(publisherId);
                //创建动态对象
                MomentVo vo = new MomentVo();
                BeanUtils.copyProperties(userInfoById,vo);
                vo.setTags(StringUtils.split(userInfoById.getTags(),","));
                //复制动态信息
                BeanUtils.copyProperties(publish,vo);
                vo.setImageContent(publish.getMedias().toArray(new String[]{}));
                //vo.setCreateDate(publish.getCreated().toString());
                //设置动态id
                vo.setId(publish.getId().toHexString());
                //默认距离
                vo.setDistance("100米");
                vo.setHasLiked(0);//是否点赞  0：未点 1:点赞
                vo.setHasLoved(0);//是否喜欢  0：未点 1:点赞
                //设置时间
                vo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
                voList.add(vo);
=======
    public PageResult<MomentVo> findFriendMoment(long page, long pagesize) {
        Long userId = UserHolder.getUserId();
        PageResult pageResult = publishApi.findFriendPublish(page,pagesize,userId);
        List<Publish> publishList = pageResult.getItems();
        List<MomentVo> list = new ArrayList<>();
        if (publishList!=null){
            for (Publish publish : publishList) {
                Long publisherId = publish.getUserId();
                UserInfo userInfo = userInfoApi.findUserInfoById(publisherId);
                MomentVo momentVo = new MomentVo();
                BeanUtils.copyProperties(userInfo,momentVo);
                momentVo.setTags(StringUtils.split(userInfo.getTags(),","));
                BeanUtils.copyProperties(publish,momentVo);
                momentVo.setId(publish.getId().toHexString());
                momentVo.setImageContent(publish.getMedias().toArray(new String[]{}));
                momentVo.setDistance("99米");
                momentVo.setHasLiked(0);
                String keyLike = "publish_like_"+userId+"_"+momentVo.getId();
                if (redisTemplate.hasKey(keyLike)){
                    momentVo.setHasLiked(1);//用户对这个动态点赞了
                }
                momentVo.setHasLoved(0);
                String keyLove = "publish_love_"+userId+"_"+momentVo.getId();
                if (redisTemplate.hasKey(keyLove)){
                    momentVo.setHasLoved(0);//用户对这个动态点喜欢了
                }
                momentVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
                list.add(momentVo);
            }
        }
        pageResult.setItems(list);
        return pageResult;
    }

    /**
     * 推荐动态
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult<MomentVo> queryRecommendPublishList(long page, long pagesize) {
        Long userId = UserHolder.getUserId();
        PageResult pageResult = publishApi.queryRecommendPublishList(page,pagesize,userId);
        List<Publish> publishList = pageResult.getItems();
        List<MomentVo> listVo = new ArrayList<>();
        if (publishList!=null){
            for (Publish publish : publishList) {
                MomentVo momentVo = new MomentVo();
                UserInfo userInfo = userInfoApi.findUserInfoById(publish.getUserId());
                BeanUtils.copyProperties(userInfo,momentVo);
                momentVo.setTags(StringUtils.split(userInfo.getTags(),","));

                BeanUtils.copyProperties(publish,momentVo);
                momentVo.setDistance("99米");
                momentVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
                momentVo.setImageContent(publish.getMedias().toArray(new String[]{}));
                momentVo.setHasLiked(0);
                String keyLike = "publish_like_"+userId+"_"+momentVo.getId();
                if (redisTemplate.hasKey(keyLike)){
                    momentVo.setHasLiked(1);//用户对这个动态点赞了
                }
                momentVo.setHasLoved(0);
                String keyLove = "publish_love_"+userId+"_"+momentVo.getId();
                if (redisTemplate.hasKey(keyLove)){
                    momentVo.setHasLoved(0);//用户对这个动态点喜欢了
                }
                momentVo.setId(publish.getId().toHexString());
                listVo.add(momentVo);
            }
        }
        pageResult.setItems(listVo);
        return pageResult;
    }

    /**
     * 我的动态
     * @param page
     * @param pagesize
     * @param userId
     * @return
     */
    public PageResult<MomentVo> findMyMoment(long page, long pagesize, Long userId) {
        PageResult pageResult = publishApi.findMyMoment(page,pagesize,userId);
        List<Publish> publishList = pageResult.getItems();
        List<MomentVo> voList = new ArrayList<>();
        if (publishList != null){
            for (Publish publish : publishList) {
                MomentVo momentVo = new MomentVo();
                UserInfo userInfo = userInfoApi.findUserInfoById(userId);
                BeanUtils.copyProperties(userInfo,momentVo);
                momentVo.setTags(StringUtils.split(userInfo.getTags(),","));
                BeanUtils.copyProperties(publish,momentVo);
                momentVo.setImageContent(publish.getMedias().toArray(new String[]{}));
                momentVo.setDistance("99米");
                momentVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
                momentVo.setId(publish.getId().toHexString());
                momentVo.setHasLiked(0);
                String keyLike = "publish_like_"+userId+"_"+momentVo.getId();
                if (redisTemplate.hasKey(keyLike)){
                    momentVo.setHasLiked(1);//用户对这个动态点赞了
                }
                momentVo.setHasLoved(0);
                String keyLove = "publish_love_"+userId+"_"+momentVo.getId();
                if (redisTemplate.hasKey(keyLove)){
                    momentVo.setHasLoved(0);//用户对这个动态点喜欢了
                }
                voList.add(momentVo);
>>>>>>> acc7004 (第4天到第8天)
            }
        }
        pageResult.setItems(voList);
        return pageResult;
    }
<<<<<<< HEAD
=======


    /**
     * 通过id查找动态
     * @param publishId
     * @return
     */
    public MomentVo findById(String publishId) {
        // 调用publishApi查询动态信息
        Publish publish = publishApi.findById(publishId);
        // 获取动态的发布者id
        Long userId = publish.getUserId();
        // 调用userInfoApi查询用户信息
        UserInfo userInfo = userInfoApi.findUserInfoById(userId);
        // 构建vo
        MomentVo vo = new MomentVo();
        // 补全vo信息
        // 复制用户详情
        BeanUtils.copyProperties(userInfo,vo);
        vo.setTags(StringUtils.split(userInfo.getTags(),","));
        // 复制动态的信息
        BeanUtils.copyProperties(publish, vo);
        vo.setImageContent(publish.getMedias().toArray(new String[]{}));
        // 设置动态的id
        vo.setId(publish.getId().toHexString());
        // 默认距离
        vo.setDistance("100米");
        String key = "publish_like_" + UserHolder.getUserId() + "_" + vo.getId();
        vo.setHasLiked(0);  //是否点赞  0：未点 1:点赞
        if(redisTemplate.hasKey(key)) {
            vo.setHasLiked(1);  //用户对这个动态点赞了
        }
        String keyLove = "publish_love_" + UserHolder.getUserId() + "_" + vo.getId();
        vo.setHasLoved(0);  //是否喜欢  0：未点 1:点赞
        if(redisTemplate.hasKey(keyLove)) {
            vo.setHasLoved(1);  //用户对这个动态喜欢了
        }
        // 设置时间
        vo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
        // 返回vo
        return vo;
    }
>>>>>>> acc7004 (第4天到第8天)
}
